package com.example.login.interceptor;
import com.example.login.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class Myinterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        User user = (User) request.getSession().getAttribute("user");
        log.debug("interceptor prehandle userinfo ==> {}", user);

        if (user == null) {
            response.setStatus(403);
            return false;
        }

        // 获取请求的URI
        String requestURI = request.getRequestURI();

        // 检查是否是登录接口
        if (requestURI.contains("/login")) {
            return true;
        }

        // 检查用户角色是否为管理员
        if (user.getJiaose() == 1) {
            // 如果是管理员，允许访问删除接口和查询接口
            if (requestURI.contains("/deleteUser") || requestURI.contains("/getUserInfo")) {
                return true;
            }
        } else {
            if (!requestURI.contains("/login") && !requestURI.contains("/deleteUser") && !requestURI.contains("/getUserInfo")) {
                return true;
            }
        }

        // 其他情况，禁止访问
        response.setStatus(403);
        return false;
    }

}
